import UserProfileStateStore from "@/store/user-profile";
import { UserProfileType } from "@/types/user-profile";
import { updateUserProfileApi } from "@/services/api/user";
import AlertService from "@/components/Global/Alert/service";
import CurrentUserIdManager from "@/utils/user-utils";
import { ResponseCode } from "@/types/api-common";
import { DEFAULT_AVATAR_URL } from "@/config/default-value";
import {useChatUserActions} from "@/hooks/chat/chat-user";

export const useUserProfileState = () => UserProfileStateStore((state) => state.state);


export const useUserProfileActions = () => {
  const state = UserProfileStateStore((state) => state.state);
  const setCurrentUserProfile = UserProfileStateStore((state) => state.actions.setCurrentUserProfile);
  const userId = CurrentUserIdManager.getUserId();
  const { upsertProfile } = useChatUserActions();


  async function getCurrentUserProfile() {
    const currentUser = state.currentUser;
    if (currentUser && currentUser.id === userId) {
      const userProfile = {
        ...currentUser,
        avatar: currentUser.avatar || DEFAULT_AVATAR_URL,
      };
      setCurrentUserProfile?.(userProfile);
    }
  }

  async function saveOrUpdateUserProfile(profile: Partial<UserProfileType>) {
    const oldProfile = state.currentUser;
    const newProfile = { ...oldProfile, ...profile, updateTime: Date.now() };

    setCurrentUserProfile?.(newProfile);
    await upsertProfile({
      id: newProfile.id,
      name: newProfile.nickname,
      avatar: newProfile.avatar,
      updateTime: newProfile.updateTime,
    });

    try {
      const res = await updateUserProfileApi(newProfile);
      if (res.data.code === ResponseCode.SUCCESS) {
        AlertService.showAlert("success", "信息更新成功");
      } else {
        throw new Error(res.data.message);
      }
    } catch (error) {
      setCurrentUserProfile?.(oldProfile);
      await upsertProfile({
        id: oldProfile.id,
        name: oldProfile.nickname,
        avatar: oldProfile.avatar,
        updateTime: oldProfile.updateTime,
      });
      AlertService.showAlert("error", `更新失败: ${error.message || "请稍后再试"}`);
    }
  }

  return {
    setCurrentUserProfile,
    getCurrentUserProfile,
    saveOrUpdateUserProfile,
  };
};
